package middleware

import (
	"golang-jwt/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	"k8s.io/klog/v2"
)

const (
	AUTH_APPID_KEY     = "X-Athena-AppID"
	AUTH_SIGN_KEY      = "X-Athena-Sign"
	AUTH_TIMESTAMP_KEY = "X-Athena-Timestamp"
	AUTH_OPERATOR_KEY  = "X-Athena-Operator"
	UDB_KEY            = "udb"
)

// 控制台调用校验（通常是由前端界面发起的操作，使用 /admin 前缀）
func AdminAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.GetHeader("jwt")
		if tokenString == "" {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token missing"})
			return
		}

		claims, err := utils.ValidateJWT(tokenString)
		if err != nil {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
			return
		}

		if claims.Username == "" {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "校验token失败, username为空, token无效"})
		}

		// 将用户信息写入 gin.Context
		ctx.Set(UDB_KEY, claims.Username)
	}
}

// API 调用校验（第三方服务或应用程序调用，使用 /api 前缀）
func ApiAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		appId := ctx.GetHeader(AUTH_APPID_KEY)
		sign := ctx.GetHeader(AUTH_SIGN_KEY)
		timestamp := ctx.GetHeader(AUTH_TIMESTAMP_KEY)
		operator := ctx.GetHeader(AUTH_OPERATOR_KEY)

		klog.Infof("appId: %v, sign: %v, timestamp: %v, operator: %v", appId, sign, timestamp, operator)
		ctx.Set(UDB_KEY, operator)
	}
}
